package com.tomise.core.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tomise.core.page.Page;
/**
 * tomise的webstar的BaseController基类
 * @author meigang
 * @date 2015-08-13
 * @version 1.0
 */
public abstract class BaseController {
	protected HttpServletRequest request;
	@Resource
	private void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	/**
	 * 常用跳转方法
	 */
	public abstract String index(HttpServletResponse arg0, ModelMap arg1);
	public abstract void query(@RequestParam Integer page, @RequestParam Integer rows,
			HttpServletRequest request, HttpServletResponse response, ModelMap map);
	/**
	 * 向request域中存key,value
	 * @param key
	 * @param value
	 */
	protected void setAttr(String key,Object value){
		this.request.setAttribute(key, value);
	}
	/**
	 * 从request域中得到key的值
	 * @param key
	 * @return
	 */
	protected Object getAttr(String key){
		return this.request.getAttribute(key);
	}
	/*设置session域*/
	protected void setSessionAttr(String key,Object value){
		this.request.getSession().setAttribute(key, value);
	}
	protected Object getSessionAttr(String key){
		return this.request.getSession().getAttribute(key);
	}
	/*获取参数*/
	protected String getPara(String key){
		return this.request.getParameter(key);
	}
	
	/**
	 * 将page数据装成jqgrid需要的分页数据
	 * @param footPage
	 * @return
	 */
	protected JSONObject toJQGridPage(Page page) {
		JSONObject jsonObject = new JSONObject();
		
		jsonObject.put("total", page.get_total());
		jsonObject.put("page", page.get_page());
		jsonObject.put("records", page.get_records());
		JSONArray array = new JSONArray();
		for(Object f : page.getList()){
			JSONObject temp = (JSONObject) JSONObject.toJSON(f);
			array.add(temp);
		}
		jsonObject.put("rows", array);
		return jsonObject;
	}
	
	public void renderText(HttpServletResponse response, String s){
		mg000(response, "text/plain;charset=UTF-8", s);
    }

    public void renderJson(HttpServletResponse response, String s){
    	mg000(response, "application/json;charset=UTF-8", s);
    }

    public void renderXml(HttpServletResponse response, String s) {
    	mg000(response, "text/xml;charset=UTF-8", s);
    }

    public void renderHtml(HttpServletResponse response, String s){
        mg000(response, "text/html;charset=UTF-8", s);
    }
    
	protected void mg000(HttpServletResponse response,String type,String str){
		response.setContentType(type);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
        try {
			response.getWriter().write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void ajaxDoneSuccess(HttpServletResponse response, String s){
        com.alibaba.fastjson.JSONObject jsonobject = new com.alibaba.fastjson.JSONObject();
        jsonobject.put("state", 1);
        jsonobject.put("statusCode", Integer.valueOf(200));
        if(StringUtils.isBlank(s))
            jsonobject.put("msg", "操作成功");
        else
            jsonobject.put("msg", s);
        renderJson(response, jsonobject.toString());
    }

    public void ajaxDoneError(HttpServletResponse response, String s){
        com.alibaba.fastjson.JSONObject jsonobject = new com.alibaba.fastjson.JSONObject();
        jsonobject.put("state", 0);
        jsonobject.put("statusCode", Integer.valueOf(300));
        if(StringUtils.isBlank(s))
            jsonobject.put("msg", "操作失败");
        else
            jsonobject.put("msg", s);
        renderJson(response, jsonobject.toString());
    }
	@InitBinder
	public void initBinder(WebDataBinder binder) {
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    dateFormat.setLenient(false);
	    //true:允许输入空值，false:不能为空值
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	/*取得ajax提交过来的json对象*/
	public net.sf.json.JSONObject getPramJson(){
        StringBuilder stringbuilder = new StringBuilder();
        Enumeration enumeration = request.getParameterNames();
        if(enumeration.hasMoreElements())
            do
            {
                if(!enumeration.hasMoreElements())
                    break;
                String s = (String)enumeration.nextElement();
                if(!"method".equalsIgnoreCase(s))
                {
                    String as[] = request.getParameterValues(s);
                    if(as.length == 1)
                    {
                        stringbuilder.append(s).append("").append(as[0]);
                    } else
                    {
                        stringbuilder.append(s).append("[]={");
                        for(int i = 0; i < as.length; i++)
                        {
                            if(i > 0)
                                stringbuilder.append(",");
                            stringbuilder.append(as[i]);
                        }

                        stringbuilder.append("}");
                    }
                }
            } while(true);
        net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(stringbuilder.toString());
        return jsonobject;
	}
	/*得到ajax中传递过来的参数*/
	public String getParaJsonStr(String key){
		net.sf.json.JSONObject jsonobject = getPramJson();
		return jsonobject.getString(key);
	}
}
